package com.bourse.core.services.cotation;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.joda.time.DateMidnight;

import com.bourse.core.utils.Cotation;
import com.bourse.core.utils.IsinCode;
import com.bourse.core.utils.TimeSerieObject;


public class CotationServiceImpl implements CotationService {

	private Logger LOGGER = Logger.getLogger(CotationServiceImpl.class) ;
	
	private CotationDataService cotationDataService;
	
	private IndiceCompoDataService indiceCompoDataService;
	
	/**
	 * @see CotationService#getIsinCode()
	 */
	public List<IsinCode> getIsinCode(){
		LOGGER.info("[Cotation Service] - Get available isin from cotation");
		Map<IsinCode, TimeSerieObject<Cotation>> cotationMap = cotationDataService.getCotations();
		return new ArrayList<IsinCode>(cotationMap.keySet());
	}
	
	/**
	 * @see CotationService#getIndiceComposition(IsinCode, DateMidnight)
	 */
	public List<IsinCode> getIndiceComposition(IsinCode isinCode, DateMidnight date){
		
		LOGGER.info("[Cotation Service] - Get indice composition for "+isinCode.getCode());
		List<IsinCode> isinCodeList = new ArrayList<IsinCode>();
		Map<IsinCode, TimeSerieObject<List<IsinCode>>> compositionMap = indiceCompoDataService.getIndiceComposition();

		TimeSerieObject<List<IsinCode>> timeSerie = compositionMap.get(isinCode);		
		if(timeSerie!=null){
			isinCodeList = timeSerie.getValue(date);
		}
		return isinCodeList;
	}
	
	
	public Cotation getCotation(IsinCode isinCode, CotationDayDate cotationDayDate){
		Map<IsinCode, TimeSerieObject<Cotation>> cotationMap = cotationDataService.getCotations();
		TimeSerieObject<Cotation> tsCotation = cotationMap.get(isinCode);
		Cotation cotation = null;
		if(tsCotation !=null){
			cotation = tsCotation.getValue(cotationDayDate.current());
			if(cotation==null){
				DateMidnight lastDateBefore = tsCotation.getLastDateBefore(cotationDayDate.current());
				Cotation lastOne = tsCotation.getValue(lastDateBefore);
				cotation = new Cotation();
				cotation.setCours(lastOne.getCours());
				cotation.setOuverture(lastOne.getCours());
				cotation.setPlusBas(lastOne.getCours());
				cotation.setPlusHaut(lastOne.getCours());
				cotation.setVolume("0");
				cotation.setIsin(isinCode);
				cotation.setDate(lastDateBefore);
			}else{
				return cotation;
			}
		}
		return cotation;
	}

	/**
	 * @param cotationDataService the cotationDataService to set
	 */
	public void setCotationDataService(CotationDataService cotationDataService) {
		this.cotationDataService = cotationDataService;
	}

	/**
	 * @param indiceCompoDataService the indiceCompoDataService to set
	 */
	public void setIndiceCompoDataService(
			IndiceCompoDataService indiceCompoDataService) {
		this.indiceCompoDataService = indiceCompoDataService;
	}

	 
	
}
